package logic

import (
	"context"
	"fmt"
	"housing/model/mysql"
	"housing/model/redis"
	"housing/pkg"

	"housing/housingrpc/housingrpc"
	"housing/housingrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserloginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserloginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserloginLogic {
	return &UserloginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserloginLogic) Userlogin(in *housingrpc.UserloginRequest) (*housingrpc.UserloginResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Client.Get("Captachalogin" + in.Phone)
	if get.Val() != in.Code {
		return nil, fmt.Errorf("验证码输入错误请重新输入")
	}
	cmd := redis.Client.Get("sendSmslogin" + in.Phone)
	if cmd.Val() != in.Sendsms {
		return nil, fmt.Errorf("短信验证码输入错误请重新输入")
	}
	var findhousing mysql.User
	mysql.DB.Debug().Where("phone = ?", in.Phone).Find(&findhousing)
	if findhousing.ID == 0 {
		return nil, fmt.Errorf("当前账号未注册请前往注册")
	}
	if findhousing.Password != pkg.Md5Password(in.Password) {
		return nil, fmt.Errorf("当前密码错误")
	}
	mysql.DB.Debug().Create(&findhousing)
	redis.Client.Del("Captachalogin" + in.Phone)
	redis.Client.Del("sendSmslong" + in.Phone)
	return &housingrpc.UserloginResponse{Id: int64(findhousing.ID)}, nil

}
